﻿using System;

namespace Lists
{
    public class List<T>
    {
        private ListNode<T> firstNode;
        private ListNode<T> lastNode;
        private string listName;

        public List(string name)
        {
            listName = name;
        }

        public List()
            :this("list")
        {
        }

        public void InsertAtFront(T insertItem)
        {
            if(IsEmpty())
                firstNode = lastNode = new ListNode<T>(insertItem);
            else
                firstNode = new ListNode<T>(insertItem, firstNode);
        }

        public void InsertAtBack(T insertItem)
        {
            if (IsEmpty())
                firstNode = lastNode = new ListNode<T>(insertItem);
            else
                lastNode = lastNode.Next = new ListNode<T>(insertItem);
        }

        public T RemoveFromFront()
        {
            if (IsEmpty())
                throw new EmptyListException(listName);

            T removeItem = firstNode.Data;

            if (firstNode == lastNode)
                firstNode = lastNode = null;
            else
                firstNode = firstNode.Next;

            return removeItem;
        }

        public T RemoveFromBack()
        {
            if (IsEmpty())
                throw new EmptyListException(listName);

            T removeItem = lastNode.Data;

            if (firstNode == lastNode)
                firstNode = lastNode = null;
            else
            {
                ListNode<T> currentNode = firstNode;

                while (currentNode.Next != lastNode)
                    currentNode = currentNode.Next;

                lastNode = currentNode;
                currentNode.Next = null;
            }

            return removeItem;
        }

        public bool IsEmpty()
        {
            return firstNode == null;
        }

        public void Display()
        {
            if (IsEmpty())
            {
                Console.WriteLine("Empty " + listName);
            }
            else
            {
                Console.Write("The " + listName + " is: ");
                ListNode<T> current = firstNode;

                while (current != null)
                {
                    Console.Write(current.Data + " ");
                    current = current.Next;
                }
            }
        }
    }
}
